<?php

namespace App\Http\Requests\UserCenter;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Validator;
use Auth;
use App\Model\Creator;
use Illuminate\Http\Exceptions\HttpResponseException;

class BeCreatorRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }


    public function addValidator()
    {
        Validator::extend('creator_is_had', function ($attribute, $value, $parameters, $validator) {
            $user = Auth::user();
            if ($user->is_sale) {
                $count = Creator::where('creator_name', $value)
                    ->where('user_id', '<>', $user->id)->count();
            } else {
                $count = Creator::where('creator_name', $value)->count();
            }
            if ($count > 0) {
                return false;
            } else {
                return true;
            }
        });

        Validator::extend('apply_is_exist', function ($attribute, $value, $parameters, $validator) {
            $user = Auth::user();
            $count = Creator::where('user_id', $user->id)
                ->where('check_passed', '=', false)->count();
            if ($count > 0) {
                return false;
            } else {
                return true;
            }
        });
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $this->addValidator();
        return [
            'creator_name' => [
                'sometimes',
                'required',
                'between:1,20',
                'regex:/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$/u',
                'creator_is_had',
                'apply_is_exist',
            ],

        ];
    }

    public function messages()
    {
        return [
            'creator_name.required' => '创作名不能为空',
            'creator_name.between' => '创作名长度只能在1-20个字符之间',
            'creator_name.regex' => '创作名只能由 汉字 字母 数字 下划线 组成',
            'creator_name.creator_is_had' => '此名称已存在',
            'creator_name.apply_is_exist' => '您已提交过申请，请等待管理员审核',
        ];
    }

    public function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        throw (new HttpResponseException(response()->json([
            'status_code' => 500,
            'error' => $validator->errors()->all(),
        ], 200)));
    }
}
